<?php

namespace fankers;

use fankers\lib\wb\Wb as WbBase;

class Wb
{
    public $_inst = null;
    public $_class = null;
    public $_access_token = '';
    public $_open_id = '';

    public function __construct($params)
    {
        ##用code 获取token信息
        $this->_class = WbBase::class;

        if (!$this->_inst) {
            $this->_inst = new $this->_class($params);
        }
    }

    /**
     * 判断类是否似可调用的
     * @param $action
     * @return bool
     */
    protected function isCall($action)
    {
        if (is_callable([$this->_inst,$action])) {
            return true;
        } else {
            return false;
        }
    }

    public function index()
    {
        ## code=CODE&state=STATE 确认授权以后跳转到当前方法 带着code
        $this->_inst->start();
        $code = $_GET['code'];
        $params = [
            'code' => $code,
        ];

        $result = $userInfo = $openidInfo = [];

        ## 获取token
        if ($this->isCall('token')) {
            $result = $this->_inst->token($params);
        }

        ## 用返回的token信息 拉取用户信息
        if (!empty($result) && $this->isCall('info')) {
            $this->_access_token = isset($result['access_token']) ? $result['access_token'] : '';
            $this->_open_id = isset($result['uid']) ? $result['uid'] : '';

            $data = [
                'access_token' => $result['access_token'],
                'uid' => $result['uid']
            ];
            $userInfo = $this->_inst->info($data);
        }
        return $userInfo;
    }
}
